﻿using Fast;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 框架启动类服务扩展
    /// </summary>
    [SkipScan]
    public static class FastStartupServiceCollectionExtensions
    {
        /// <summary>
        /// 添加 Startup 
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        internal static IServiceCollection AddStartups(this IServiceCollection services)
        {
            AddStartupServices(services, options => options.DiscoverFastStartup());
            return services;
        }

        /// <summary>
        /// 添加Stratup服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        private static IServiceCollection AddStartupServices(this IServiceCollection services, Action<FastStartupOptions> configure)
        {
            Check.NotNull(services, nameof(services));
            Check.NotNull(configure, nameof(configure));

            var options = new FastStartupOptions();
            configure(options);

            var startupManager = new StartupManager(options);
            services.AddSingleton<IStartupManager>(startupManager);

            if (options.FastStartups.Count == 0)
            {
                return services;
            }

            startupManager.ConfigureServices(new ConfigureServicesContext(services));

            return services;
        }
    }
}
